package com.kifas.service.dataaccess;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kifas.entity.PenerimaanDetailEntity;
import com.kifas.entity.PenerimaanEntity;

@Repository
public class PenerimaanDao {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(PenerimaanDao.class);

	private static String ALL_PENERIMAAN = "from PenerimaanEntity p ";
	@SuppressWarnings("unused")
	private static String PENERIMAAN_AND_DETAIL = ALL_PENERIMAAN
			+ "left join fetch PenerimaanDetailEntity pd ";
	private static String PENERIMAAN_BY_ID = ALL_PENERIMAAN
			+ "where p.idPenerimaan = :idPenerimaan ";
	private static String ALL_PENERIMAAN_DETAIL = "from PenerimaanDetailEntity pd ";
	private static String PENERIMAAN_DETAIL_BY_PARENT = ALL_PENERIMAAN_DETAIL
			+ "where pd.pembelian = :pembelian";

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<PenerimaanEntity> getPenerimaans() {
		return sessionFactory.getCurrentSession().createQuery(ALL_PENERIMAAN)
				.list();
	}

	public PenerimaanEntity getPenerimaan(Long idPenerimaan) {
		return (PenerimaanEntity) sessionFactory.getCurrentSession()
				.createQuery(PENERIMAAN_BY_ID)
				.setLong("idPenerimaan", idPenerimaan).uniqueResult();
	}

	public void insert(PenerimaanEntity penerimaan) throws Exception {
		sessionFactory.getCurrentSession().save(penerimaan);
		for (PenerimaanDetailEntity detail : penerimaan.getPenerimaanDetails()) {
			sessionFactory.getCurrentSession().save(detail);
		}
	}

	@SuppressWarnings("unchecked")
	public List<PenerimaanDetailEntity> getPenerimaanDetails(
			PenerimaanEntity penerimaan) {
		return sessionFactory.getCurrentSession()
				.createQuery(PENERIMAAN_DETAIL_BY_PARENT)
				.setEntity("penerimaan", penerimaan).list();
	}
}
